package com.example.jussi.threadsocketdemo;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ConnectException;
import java.net.Socket;

/**
 * Created by admin on 2018/12/6.
 */

public class ClientThread implements Runnable {
    Handler handler, revHandler;
    String ip;
    InputStream inputStream;
    OutputStream outputStream;
    BufferedReader reader;
    public ClientThread(Handler handler, String ip){
        this.handler = handler;
        this.ip = ip;
    }
    @Override
    public void run() {
        try {
            Log.d("----------------", ip);
            Socket socket = new Socket(this.ip, 30008);
            outputStream = socket.getOutputStream();
            inputStream = socket.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            new Thread(){
                @Override
                public void run() {
                    String string;
                    try {
                        while ( (string = reader.readLine()) != null ){
                            Message message = new Message();
                            message.what = 0x01;
                            message.obj = string;
                            handler.sendMessage(message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            Looper.prepare();
            revHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == 0x02) {
                        String string = msg.obj.toString();
                        Log.d("-----------", string);
                        PrintStream printStream = new PrintStream(outputStream);
                        printStream.println(string);
                    }
                }
            };
            Looper.loop();
        } catch (ConnectException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}